<?php
class Facebook
{
	private $CI;	
	 public function __construct()
    {
        if (!isset($this->CI))
        {
            $this->CI =& get_instance();
        }
	}
	public static function config(){
		########## app ID and app SECRET (Replace with yours) #############
	$config['appId'] = '215897145260007'; //Facebook App ID
	$config['appSecret'] = '58add3fb7f9b1b226119de7ba4cec1a9'; // Facebook App Secret
	$config['return_url'] = 'http://localhost/facebookconnect/';  //path to script folder
	$config['fbPermissions'] = 'user_friends,email,public_profile'; // more permissions : https://developers.facebook.com/docs/authentication/permissions/
		return $config;
	}
	
	public static function checkLogin($sesslogin){
		if(!isset($sesslogin)){
			return '<a rel="nofollow" class="login-social fblogin-button" onClick="javascript:CallAfterLogin();return false;" href="#" rel="facebook"></a>';
		}else{
			//echo 'Hi '. $_SESSION['user_name'].'! You are Logged in to facebook, <a href="?logout=1">Log Out</a>.';
			return $sesslogin;
		}
	}
	
	public static function channel(){
		$cache_expire = 60*60*24*365;
		header("Pragma: public");
		header("Cache-Control: max-age=".$cache_expire);
		header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$cache_expire) . ' GMT');
		echo '<script src="//connect.facebook.net/en_US/all.js"></script>';
	}
	public static function logout(){
		session_destroy();
	}
	
	public function processFace($content,$parentid){
		self::config();
		require_once('inc/facebook.php' );
		/* Detect HTTP_X_REQUESTED_WITH header sent by all recent browsers that support AJAX requests. */
		if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
		{		
		
			//initialize facebook sdk
			$facebook = new Facebook(array(
				'appId' => $appId,
				'secret' => $appSecret,
			));
			
			$fbuser = $facebook->getUser();
			
			if ($fbuser) {
				try {
					// Proceed knowing you have a logged in user who's authenticated.
					$me = $facebook->api('/me'); //user
					$uid = $facebook->getUser();
				}
				catch (FacebookApiException $e) 
				{
					//echo error_log($e);
					$fbuser = null;
				}
			}
			
			// redirect user to facebook login page if empty data or fresh login requires
			if (!$fbuser){
				$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$return_url, false));
				header('Location: '.$loginUrl);
			}
			
			//user details
			$fullname = $me['first_name'].' '.$me['last_name'];
			$email = $me['email'];
		
			/* connect to mysql using mysqli */
			$this->CI->load->model('member_model','member');
			$this->CI->load->model('news_model','news');
			//Check user id in our database	
			$UserCount = $this->CI->member->checkLogin($email); 
			$member_id=$UserCount->memberid;
			if($UserCount)
			{	
				//add comment
				$this->CI->news->addComment($content,$parentid,$email,$fullname,$member_id);
				login_user(true,$me['first_name'].' '.$me['last_name']);
				trit('user exist');
			}
			else
			{	// add user from face inte member
				$avatar="https://graph.facebook.com/'.$uid.'/picture?type=small";
				$this->CI->member->add($email,$fullname,$avatar);
				//add comment   Note: cho nay chua logic lam
				$UserCount = $this->CI->member->checkLogin($email); 
				$member_id=$UserCount->memberid;
				$this->CI->news->addComment($content,$parentid,$email,$fullname,$member_id);
				trit('user no exist');		
			}
			
		}
	}
	function login_user($loggedin,$user_name)
	{
		/*
		function stores some session variables to imitate user login. 
		We will use these session variables to keep user logged in, until s/he clicks log-out link.
		*/
		$_SESSION['logged_in']=$loggedin;
		$_SESSION['user_name']=$user_name;
	}
}
